﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace BST250301TestStand.Models.Utils
{
    internal class TCP
    {
        private TcpClient _client;
        private NetworkStream _stream;
        private Task _receiveTask;
        private CancellationTokenSource _cancellationTokenSource;

        public event EventHandler<string> DataReceived;
        public event EventHandler Disconnected;

        // 服务器信息
        private string _ServerIp = "127.0.0.1";
        private int _ServerPort = 8011;
        public TCP(string ip, int port)
        {
            _ServerIp = ip;
            _ServerPort = port;
        }
        /// <summary>
        /// 建立TCP长连接，并启动后台接收任务
        /// </summary>
        public async Task<bool> ConnectAsync()
        {
            try
            {
                _client = new TcpClient();
                await _client.ConnectAsync(_ServerIp, _ServerPort);
                _stream = _client.GetStream();
                _cancellationTokenSource = new CancellationTokenSource();

                // 启动后台接收任务
                _receiveTask = Task.Run(async () => await ReceiveDataAsync(_cancellationTokenSource.Token));
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 发送数据到服务器
        /// </summary>
        public async Task<bool> SendAsync(string message)
        {
            if (_stream == null || !_client.Connected)
            {
                //MessageBox.Show("错误: 连接未建立或已断开。");
                return false;
            }

            try
            {
                byte[] buffer = Encoding.ASCII.GetBytes(message);
                await _stream.WriteAsync(buffer, 0, buffer.Length);
                //MessageBox.Show($"已发送: {message}");
                return true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"发送失败: {ex.Message}");
                //Disconnect();
                return false;
            }
        }

        /// <summary>
        /// 后台持续接收数据的方法
        /// </summary>
        private async Task ReceiveDataAsync(CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[1024];

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                    if (bytesRead == 0)
                    {
                        // 服务器断开连接
                        MessageBox.Show("服务器已断开连接。");
                        break;
                    }

                    string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);

                    // 触发事件通知外部调用者
                    DataReceived?.Invoke(this, receivedData);
                }
                catch (OperationCanceledException)
                {
                    // 任务被取消，正常退出循环
                    break;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"接收数据失败: {ex.Message}");
                    break;
                }
            }

            // 确保连接在退出循环时被清理
            Disconnect();
        }

        /// <summary>
        /// 断开连接并清理资源
        /// </summary>
        public void Disconnect()
        {
            // 如果任务正在运行，则取消它
            if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
            {
                _cancellationTokenSource.Cancel();
            }

            _stream?.Dispose();
            _client?.Dispose();

            // 触发断开连接事件
            Disconnected?.Invoke(this, EventArgs.Empty);

            MessageBox.Show("TCP连接已断开。");
        }
    }
}